//
//  RNTOneLogin.m
//  rzc_app
//
//  Created by 孙磊 on 2019/5/16.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "RNTOneLogin.h"
#import <OneLoginSDK/OneLoginSDK.h>
//#import "OLPrivacyTermItem.h"
#define ScreenWidth [UIScreen mainScreen].bounds.size.width
#define ScreenHeight [UIScreen mainScreen].bounds.size.height
#define StatusBarHeight [[UIApplication sharedApplication] statusBarFrame].size.height



@interface RNTOneLogin ()<OneLoginDelegate>
@end
@implementation RNTOneLogin {
  RCTPromiseResolveBlock _resolveBlock;
  RCTPromiseRejectBlock _rejectBlock;
  NSString *_agreementCustom;
  OLAuthViewModel *viewModel;
}
- (instancetype)init {
  return self;
}
@synthesize bridge = _bridge;
//除了实现RCTBridgeModule协议外，类还需要包含RCT_EXPORT_MODULE()宏。这个宏可以添加
//一个参数用来指定在JavaScript中访问这个模块的名字
//通常不指定名字，默认使用Objective-C类的名字
RCT_EXPORT_MODULE();
- (dispatch_queue_t)methodQueue
{
  return dispatch_get_main_queue();
}

+ (BOOL)requiresMainQueueSetup
{
  return YES;
}
//使用RCT_EXPORT_METHOD()宏声明需要提供给React Native组件调用的方法
RCT_EXPORT_METHOD(sendMessage:(NSString *)msg resolver: (RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
{
  _resolveBlock=resolve;
  _rejectBlock=reject;
  _agreementCustom=msg;
  //在调试窗口中打印React Native组件调用此函数时携带的参数
  NSLog(@"收到的来自React Native的消息");
  //检测收到的消息是否为 JSON格式
  [OneLogin setDelegate:self];
  [OneLogin preGetTokenWithCompletion:^(NSDictionary * _Nonnull sender) {
    NSLog(@"sender: %@", sender.description);
    NSNumber *status = [sender objectForKey:@"status"];
    if (status && [@(200) isEqualToNumber:status]) {
      // 预取号成功
      [self requestToken];
    }
    else {
      // 预取号失败
      NSDictionary *res = @{@"status": @500,@"msg":@"预取号失败"};
        self->_resolveBlock(res);
    }
  }];
}
- (void)requestToken {
  viewModel = [OLAuthViewModel new];
  viewModel.naviTitle = [[NSMutableAttributedString alloc] initWithString:@""];
  viewModel.naviBackImage = [UIImage imageNamed:@"onelogin_back"];
  viewModel.naviHidden = YES;
  viewModel.logoHidden = YES;
  double logoHeight = ScreenWidth/750*282;
  double currentWidth = ScreenWidth-112;
  // -------------- 手机号设置 -------------------
  OLRect phoneNumRect = {logoHeight-20+50+27+15+15+45+20, 0, 0, 0, 0,0, {currentWidth, 62}};
  viewModel.phoneNumRect = phoneNumRect;
  viewModel.phoneNumColor = UIColor.blackColor; // 颜色
  viewModel.phoneNumFont = [UIFont boldSystemFontOfSize:18]; // 字体
  // -------------- 切换账号设置 -------------------
  viewModel.switchButtonColor = [self creatColorWithHexString:@"#444444"];
  viewModel.switchButtonFont = [UIFont systemFontOfSize:16];  // 切换按钮字体
  viewModel.switchButtonText = @"切换手机号";  // 切换按钮文案
  viewModel.switchButtonHidden = NO; // 是否隐藏切换按钮，默认不隐藏
  OLRect switchButtonRect =  {logoHeight-20+50+27+15+15+45+15+62+15+62, 0, 0, 0, 0, 0, {currentWidth, 62}};
  viewModel.switchButtonRect = switchButtonRect;
  // -------------- 授权登录按钮设置 -------------------
  viewModel.authButtonImages = @[[UIImage imageNamed:@"onelogin_btn_bg"],[UIImage imageNamed:@"onelogin_btn_bg_unactive"],[UIImage imageNamed:@"onelogin_btn_bg"]];   // 授权按钮背景图片
  viewModel.authButtonTitle = [[NSAttributedString alloc] initWithString:@"登录"
                                                              attributes:@{NSForegroundColorAttributeName : UIColor.whiteColor,
                                                                           NSFontAttributeName : [UIFont boldSystemFontOfSize:18]
                                                                           }];  // 导航栏标题
  OLRect authButtonRect =  {logoHeight-20+50+27+15+15+45+15+62, 0, 0, 0, 0, 0, {currentWidth, 62}}; // 切换按钮偏移、大小设置，偏移量和大小设置值需大于0，否则取默认值，默认可不设置
  viewModel.authButtonRect = authButtonRect;
  viewModel.authButtonCornerRadius = 31; // 授权按钮圆角，默认为0
  viewModel.sloganTextColor = UIColor.whiteColor;
  // -------------- 自定义UI设置，如，可以在授权页面添加三方登录入口 -------------------
  viewModel.customUIHandler = ^(UIView * _Nonnull customAreaView) {
    UIImageView *appLogo = [[UIImageView alloc] initWithFrame:CGRectMake(0 ,-StatusBarHeight, ScreenWidth, logoHeight)];
    appLogo.image = [UIImage imageNamed:@"logo_auth"];
    [customAreaView addSubview:appLogo];
    UILabel *firstTitle = [[UILabel alloc] initWithFrame:CGRectMake(0 ,logoHeight-20+50, ScreenWidth, 27)];
    firstTitle.numberOfLines = 0;
    firstTitle.text = @"登录";
    firstTitle.font =[UIFont boldSystemFontOfSize: 27];
    firstTitle.textColor = [UIColor colorWithRed:60/255.0 green:60/255.0 blue:60/255.0 alpha:1.0];
    firstTitle.textAlignment = NSTextAlignmentCenter;
    [customAreaView addSubview:firstTitle];
    UILabel *secondTitle = [[UILabel alloc] initWithFrame:CGRectMake(0 ,logoHeight-20+50+27+5, ScreenWidth, 15)];
    secondTitle.numberOfLines = 0;
    secondTitle.text = @"Sign In";
    secondTitle.font =[UIFont boldSystemFontOfSize: 12];
    secondTitle.textColor = [UIColor colorWithRed:68/255.0 green:68/255.0 blue:68/255.0 alpha:1.0];
    secondTitle.textAlignment = NSTextAlignmentCenter;
    [customAreaView addSubview:secondTitle];
    UIView *phoneNumBg = [[UIView alloc] initWithFrame:CGRectMake((ScreenWidth-currentWidth)/2 ,logoHeight-20+50+27+15+15+45, currentWidth, 62)];
    phoneNumBg.layer.masksToBounds = YES;
    phoneNumBg.layer.cornerRadius = 31;
    phoneNumBg.layer.borderWidth = 1;
    phoneNumBg.layer.borderColor = [[UIColor colorWithRed:60/255.0 green:60/255.0 blue:60/255.0 alpha:1] CGColor];
    [customAreaView addSubview:phoneNumBg];
  };
  
  viewModel.checkBoxSize = CGSizeMake(16, 16);
  viewModel.checkedImage = [UIImage imageNamed:@"checked"];
  viewModel.uncheckedImage = [UIImage imageNamed:@"check-arrow"];
  viewModel.termTextColor = [self creatColorWithHexString:@"#000000"];
  viewModel.privacyTermsAttributes = @{ NSForegroundColorAttributeName:[self creatColorWithHexString:@"#000000"]};
  viewModel.additionalPrivacyTerms = @[[[OLPrivacyTermItem alloc]initWithTitle:@"人职初条款" linkURL:[[NSURL alloc] initWithString:_agreementCustom]]];
  viewModel.webNaviTitle = [[NSAttributedString alloc] initWithString:@"人职初条款"
                                                          attributes:@{NSForegroundColorAttributeName : UIColor.whiteColor,
                                                                       NSFontAttributeName : [UIFont boldSystemFontOfSize:18]
                                                                       }];  //
  UIViewController *controller = (UIViewController*)[[[UIApplication sharedApplication] keyWindow] rootViewController];
  [OneLogin requestTokenWithViewController:controller viewModel:viewModel completion:^(NSDictionary * _Nullable result) {
    [OneLogin dismissAuthViewController:nil];
    self->_resolveBlock(result);
  }];
}

/**
 OneLoginDelegate
 */

/**
 用户点击了授权页面的返回按钮
 */
- (void)userDidDismissAuthViewController {
  NSLog(@"userDidDismissAuthViewController");
  NSDictionary *res = @{@"status": @300,@"msg":@"取消一键登录"};
  [OneLogin dismissAuthViewController:nil];
  _resolveBlock(res);
}

/**
 用户点击了授权页面的"切换账户"按钮
 */
- (void)userDidSwitchAccount {
  NSLog(@"userDidSwitchAccount");
  NSDictionary *res = @{@"status": @500,@"msg":@"切换账号"};
  [OneLogin dismissAuthViewController:nil];
  self->_resolveBlock(res);
}

/**
 用户点击了授权页面的"切换账户"按钮
 */
- (UIImage *)createImageWithColor:(NSString *)hexString {
  
  CGRect rect = CGRectMake(0, 0, 327, 46); //图片尺寸
  
  UIGraphicsBeginImageContext(rect.size); //填充画笔
  
  CGContextRef context = UIGraphicsGetCurrentContext(); //根据所传颜色绘制
  
  CGContextSetFillColorWithColor(context, [self creatColorWithHexString:hexString].CGColor);
  
  CGContextFillRect(context, rect); //联系显示区域
  
  UIImage * image = UIGraphicsGetImageFromCurrentImageContext(); // 得到图片信息
  
  UIGraphicsEndImageContext(); //消除画笔
  
  return image;
  
}


- (UIColor *) creatColorWithHexString: (NSString *)hexString
{
  NSString *cString = [[hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
  
  //hexString应该6到8个字符
  if ([cString length] < 6) {
    return [UIColor clearColor];
  }
  
  //如果hexString 有@"0X"前缀
  if ([cString hasPrefix:@"0X"])
    cString = [cString substringFromIndex:2];
  
  //如果hexString 有@"#""前缀
  if ([cString hasPrefix:@"#"])
    cString = [cString substringFromIndex:1];
  if ([cString length] != 6)
    return [UIColor clearColor];
  
  //RGB转换
  NSRange range;
  range.location = 0;
  range.length = 2;
  
  //R
  NSString *rString = [cString substringWithRange:range];
  
  //G
  range.location = 2;
  NSString *gString = [cString substringWithRange:range];
  
  //B
  range.location = 4;
  NSString *bString = [cString substringWithRange:range];
  
  //
  unsigned int r, g, b;
  [[NSScanner scannerWithString:rString] scanHexInt:&r];
  [[NSScanner scannerWithString:gString] scanHexInt:&g];
  [[NSScanner scannerWithString:bString] scanHexInt:&b];
  
  return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
//使用该方法不会模糊，根据屏幕密度计算
- (UIImage *)convertViewToImage:(UIView *)view {
  
  UIImage *imageRet = [[UIImage alloc]init];
  //UIGraphicsBeginImageContextWithOptions(区域大小, 是否是非透明的, 屏幕密度);
  UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, [UIScreen mainScreen].scale);
  [view.layer renderInContext:UIGraphicsGetCurrentContext()];
  imageRet = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return imageRet;
  
}@end
